package com.task.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger.TriggerState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.task.bean.TaskRunBean;
import com.task.util.ClassScanUtil;
import com.task.util.StringUtil;

@Component
public class JobUtil {
	
	private Logger log=LoggerFactory.getLogger(JobUtil.class);
	
     @Autowired
     @Qualifier("scheduler")
     private Scheduler scheduler;
     
     /**
      * 新建一个任务
      */     
     public Map<String,Object> addJob(TaskRunBean tb) throws Exception  {
         
             SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
             Date date=df.parse(tb.getStartTime());
         
             if (!CronExpression.isValidExpression(tb.getCorn())) {
                return StringUtil.returnMap("F","Corn表达式不正确!");   //表达式格式不正确
            }                            
            JobDetail jobDetail=null;
            //Class task=ClassScanUtil.getClassScanUtil().getClass(tb.getName());
            Class task=ClassScanUtil.getClassScanUtil().getClass("JobOne");
            if(null==task) {
            	log.info("===任务类:"+tb.getName()+"未找到");
            	return StringUtil.returnMap("F",tb.getName()+"任务未找到!");
            }
            jobDetail = JobBuilder.newJob(task).withIdentity(tb.getJobName(), tb.getJobGroup()).build();
            //表达式调度构建器(即任务执行的时间,不立即执行)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(tb.getCorn()).withMisfireHandlingInstructionDoNothing();

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(tb.getJobName(), tb.getJobGroup()).startAt(date)
                    .withSchedule(scheduleBuilder).build();
                                 
            //传递参数
            jobDetail.getJobDataMap().put("taskBean", tb);
            
            scheduler.scheduleJob(jobDetail, trigger);
           // pauseJob(appQuartz.getJobName(),appQuartz.getJobGroup());
            return StringUtil.returnSucess();
        } 
         /**
           * 获取Job状态
          * state的值代表该任务触发器的状态：
          * NONE:0 不存在
          * NORMAL:1 正常
          * PAUSED:2  暂停
          * COMPLETE:3  完成
          * ERROR:4  错误
          * BLOCKED:5 阻塞
          * @param jobName
          * @param jobGroup
          * @return
          * @throws SchedulerException
          */
         public TriggerState getJobState(String jobName, String jobGroup) throws SchedulerException {             
             TriggerKey triggerKey = new TriggerKey(jobName, jobGroup);    
             return scheduler.getTriggerState(triggerKey);
           }
         
         //暂停所有任务
         public void pauseAllJob() throws SchedulerException {            
             scheduler.pauseAll();
          }
        
        //暂停任务
        public Map<String,Object> pauseJob(String jobName, String jobGroup) throws SchedulerException {            
            JobKey jobKey = new JobKey(jobName, jobGroup);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                 return StringUtil.returnMap("F", "任务未在执行列表");
            }else {
                 scheduler.pauseJob(jobKey);
                 return StringUtil.returnSucess();
            }
                                         
        }
        
        //恢复所有任务
        public void resumeAllJob() throws SchedulerException {            
            scheduler.resumeAll();
        }
        
        // 恢复某个任务
        public Map<String,Object> resumeJob(String jobName, String jobGroup) throws SchedulerException {
            
            JobKey jobKey = new JobKey(jobName, jobGroup);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
            	 return StringUtil.returnMap("F", "任务未在执行列表");
            }else {               
                scheduler.resumeJob(jobKey);
                return StringUtil.returnSucess();
            }
        }
        
        //删除某个任务
        public Map<String,Object>  deleteJob(String jobName, String jobGroup) throws SchedulerException {            
            JobKey jobKey = new JobKey(jobName, jobGroup);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null ) {
            	return StringUtil.returnMap("F", "任务未在执行列表");
            }else {
                 scheduler.deleteJob(jobKey);
                 return StringUtil.returnSucess();
            }  
           
        }
        
        //修改任务
        public Map<String,Object>   modifyJob(TaskRunBean tb) throws SchedulerException {            
            if (!CronExpression.isValidExpression(tb.getCorn())) {
            	return StringUtil.returnMap("F","Corn表达式不正确!"); 
            }
            TriggerKey triggerKey = TriggerKey.triggerKey(tb.getJobName(),tb.getJobGroup());            
            JobKey jobKey = new JobKey(tb.getJobName(),tb.getJobGroup());
            if (scheduler.checkExists(jobKey) && scheduler.checkExists(triggerKey)) {
                CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);            
                //表达式调度构建器,不立即执行
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(tb.getCorn()).withMisfireHandlingInstructionDoNothing();
                //按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder).build();
                //修改参数
                if(!StringUtil.isNUll(tb.getParam())) {
                    trigger.getJobDataMap().put("invokeParam",tb.getParam());
                }                
                //按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);                                                
                return StringUtil.returnSucess();                   
            }else {
            	return StringUtil.returnMap("F", "任务未在执行列表");
            }    
            
        }
        
       /***立刻触发执行
        * @param tb
        * @throws SchedulerException
        */
       public void immediateRun(TaskRunBean tb) throws SchedulerException {
    	   JobKey jobKey = new JobKey(tb.getJobName(),tb.getJobGroup());
    	   this.scheduler.triggerJob(jobKey);
       }

}